#include "head.h"

FILE* error_stream;
FILE* info_stream;
FILE* debug_stream;

// 父子进程间通信的管道
int pipe_fd[2];

int main(void)
{
    if(pipe(pipe_fd) == -1)
        error(1, errno, "pipe");

    if(fork() != 0)
    {
        // 父进程
        signal(SIGINT, handler);

        wait(NULL);
        printf("子进程已退出\n");
        exit(0);
    }

    error_stream = fopen("error.log", "a+");   
    info_stream = fopen("info.log", "a+");   
    debug_stream = fopen("debug.log", "a+");   
    freopen("error.log","a+",stderr);             
    
    ERROR_CHECK(1, 1, "huzhu");

    
    HONG("info", "进程开始%s", "");
    // 子进程分离父进程的进程组
    setpgid(0, 0);

    // 创建主线程专属 mysql 连接
    MYSQL* mysql = malloc(sizeof(MYSQL));
    MysqlInit(mysql);
    ERROR_CHECK(mysql, NULL, "MysqlInit");
    // 创建线程池
    pool_t* pool = create_pool();

    // TCP连接
    int fd;
    tcp(&fd);

    // epoll监控请求
    int epoll_fd = epoll_create(1);
    epoll_add(epoll_fd, fd);
    epoll_add(epoll_fd, pipe_fd[0]);

    // 初始化时间队列 和 hash 表
    time_queue_t time_queue;
    bzero(&time_queue, sizeof(time_queue));
    time_hash_t hash;
    bzero(&hash, sizeof(hash));

    // 分发请求
    while(1)
    {
        struct epoll_event events[EVENT_SIZE];
        bzero(events, sizeof(events));

        int count = epoll_wait(epoll_fd, events, EVENT_SIZE, 1000);

        for(int i = 0; i < count; ++i)
        {
            int current_fd = events[i].data.fd;
            if(current_fd == fd)
                new_link(current_fd, epoll_fd, fd, &time_queue, &hash);
            else if(current_fd == pipe_fd[0])
                __exit__(pool);
            else
                analyse(current_fd, epoll_fd, pool, mysql, &time_queue, &hash);
        }

        time_t t = time(NULL);

        // overtime_eliminate_time_queue(&time_queue, &hash, t, epoll_fd);
    }
    free(mysql);
    return 0;
}

